package com.douqu.game.core.entity.ext;

import com.bean.core.buffer.ByteBuffer;
import com.douqu.game.core.config.StableDataConfig;
import com.douqu.game.core.config.common.GoodsData;
import com.douqu.game.core.config.task.ActiveBoxConfig;
import com.douqu.game.core.config.task.GrowUpBoxConfig;
import com.douqu.game.core.config.task.TaskConfig;
import com.douqu.game.core.controller.PlayerController;
import com.douqu.game.core.e.E_StableDataType;
import com.douqu.game.core.entity.Player;
import com.douqu.game.core.entity.db.TaskDB;
import com.douqu.game.core.factory.*;
import com.douqu.game.core.protobuf.SGCommonProto;
import com.douqu.game.core.protobuf.SGMainProto;
import com.douqu.game.core.protobuf.SGTaskProto;
import com.douqu.game.core.util.CoreUtils;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

public class TaskInfo extends ExtInfo {
    /**
     * 当前成长值
     */
    public int currentGrowthValue;

    /**
     * 每日活跃值
     */
    public int everyActiveValue;

    /**
     * 玩家进行中的主线任务
     */
    public Map<Integer, TaskDB> underwayMainTaskMap;

    /**
     * 玩家已完成的主线任务
     */
    public List<Integer> finishTasks;

    /**
     * 玩家进行中的支线任务
     */
    public Map<Integer, TaskDB> underwayBranchTaskMap;

    /**
     * 日常任务
     */
    public Map<Integer, TaskDB> everyDayTaskMap;

    /**
     * 支线已领取宝箱
     */
    public List<Integer> branchTaskBox;

    /**
     * 日常已领取宝箱
     */
    public List<Integer> everyDayBox;

    /**
     * 重置每日任务的时间
     */
    public long restEveryTaskTime;

    public TaskInfo(Player player) {
        super(player);

        underwayMainTaskMap = new ConcurrentHashMap<>();
        finishTasks = new CopyOnWriteArrayList<>();
        underwayBranchTaskMap = new ConcurrentHashMap<>();
        everyDayTaskMap = new ConcurrentHashMap<>();
        branchTaskBox = new CopyOnWriteArrayList<>();
        everyDayBox = new CopyOnWriteArrayList<>();
    }

    @Override
    public void init() {
        restEveryTaskTime = DataFactory.currentTime;
        taskInit();
    }

    @Override
    public void reset() {
        everyDayBox = new CopyOnWriteArrayList<>();
        everyActiveValue = 0;
        everyDayTaskMap = new ConcurrentHashMap<>();
        restEveryTaskTime = DataFactory.currentTime;
        everyRefresh();
    }

    @Override
    public void checkReset() {
        // 每日的已领奖列表要重置，每日活跃要重置，每日任务要重置
        if (!CoreUtils.isTodayByOffset(restEveryTaskTime, DataFactory.currentTime,
                ConstantFactory.DEFAULT_RESET_FRESH_TIMES_HOUR))
            reset();
    }

    @Override
    public void checkInit() {
    }

    @Override
    public void writeTo(ByteBuffer buffer) {
        buffer.writeByte(underwayMainTaskMap.size());
        for (TaskDB taskDB : underwayMainTaskMap.values()) {
            taskDB.writeTo(buffer);
        }

        buffer.writeShort(finishTasks.size());
        for (Integer id : finishTasks) {
            buffer.writeInt(id);
        }

        buffer.writeByte(underwayBranchTaskMap.size());
        for (TaskDB taskDB : underwayBranchTaskMap.values()) {
            taskDB.writeTo(buffer);
        }

        buffer.writeByte(everyDayTaskMap.size());
        for (TaskDB taskDB : everyDayTaskMap.values()) {
            taskDB.writeTo(buffer);
        }

        buffer.writeByte(branchTaskBox.size());
        for (Integer id : branchTaskBox) {
            buffer.writeInt(id);
        }

        buffer.writeByte(everyDayBox.size());
        for (Integer id : everyDayBox) {
            buffer.writeInt(id);
        }

        buffer.writeShort(currentGrowthValue);
        buffer.writeShort(everyActiveValue);
        buffer.writeLong(restEveryTaskTime);
    }

    @Override
    public void loadFrom(ByteBuffer buffer) {

        // [1, 17, 39, 0, 0, 0, 0, 1, 17, 39, 0, 0]
        int size = buffer.readByte();
        TaskDB taskDB = null;
        for (int i = 0; i < size; i++) {
            taskDB = new TaskDB();
            taskDB.loadFrom(buffer);
            if (taskDB.getConfig() == null) {
                try {
                    throw new Exception("Load TaskInfo underwayMainTaskMap Task is Null -> " + taskDB.id);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else
                underwayMainTaskMap.put(taskDB.id, taskDB);
        }

        size = buffer.readShort();
        int taskId = 0;
        for (int i = 0; i < size; i++) {
            taskId = buffer.readInt();
            if (DataFactory.getInstance().getGameObject(DataFactory.TASK_KEY, taskId) == null) {
                try {
                    throw new Exception("Load TaskInfo doneMainTasks Task is Null -> " + taskId);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else
                finishTasks.add(taskId);
        }

        size = buffer.readByte();
        for (int i = 0; i < size; i++) {
            taskDB = new TaskDB();
            taskDB.loadFrom(buffer);
            if (taskDB.getConfig() == null) {
                try {
                    throw new Exception("Load TaskInfo underwayBranchTaskMap Task is Null -> " + taskDB.id);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else
                underwayBranchTaskMap.put(taskDB.id, taskDB);
        }

        size = buffer.readByte();
        for (int i = 0; i < size; i++) {
            taskDB = new TaskDB();
            taskDB.loadFrom(buffer);
            if (taskDB.getConfig() == null) {
                try {
                    throw new Exception("Load TaskInfo everyDayTaskMap Task is Null -> " + taskDB.id);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else
                everyDayTaskMap.put(taskDB.id, taskDB);
        }

        size = buffer.readByte();
        for (int i = 0; i < size; i++) {
            branchTaskBox.add(buffer.readInt());
        }

        size = buffer.readByte();
        for (int i = 0; i < size; i++) {
            everyDayBox.add(buffer.readInt());
        }
        currentGrowthValue = buffer.readShort();
        everyActiveValue = buffer.readShort();
        restEveryTaskTime = buffer.readLong();

        // 任务映射
        taskMapped(underwayMainTaskMap);
        taskMapped(underwayBranchTaskMap);
        taskMapped(everyDayTaskMap);
    }

    /**
     * 初始化任务下发
     */
    public void taskInit() {
        StableDataConfig stableDataConfig = DataFactory.getInstance().getGameObject(DataFactory.STABLE_DATA_KEY,
                E_StableDataType.TASK_GROUP_ID.getCode());
        if (stableDataConfig == null) {
            return;
        }

        List<TaskConfig> list = DataFactory.getInstance().getDataList(DataFactory.TASK_KEY);
        list.stream().filter(v -> v.takeGrade <= player.getLv() && v.sequence == 1).forEach(v -> {
            if (v.type == SGCommonProto.E_TASK_TYPE.TASK_TYPE_MAIN_LINE_VALUE && v.groupId == stableDataConfig.intValue
                    && CoreUtils.isFunctionUnLock(FunctionFactory.UNLOCK_MAIN_TASK, player)) {
                underwayMainTaskMap.put(v.id, new TaskDB(v.id)); // 添加主线
            } else if (v.type == SGCommonProto.E_TASK_TYPE.TASK_TYPE_BRANCH_LINE_VALUE
                    && CoreUtils.isFunctionUnLock(FunctionFactory.UNLOCK_BRANCH_TASK, player)) {
                underwayBranchTaskMap.put(v.id, new TaskDB(v.id)); // 添加支线
            }
            //else if (v.type == SGCommonProto.E_TASK_TYPE.TASK_TYPE_EVERYDAY_VALUE
            //        && CoreUtils.isFunctionUnLock(FunctionFactory.UNLOCK_EVERY_TASK, player)) {
            //    everyDayTaskMap.put(v.id, new TaskDB(v.id)); // 添加每日任务
            //}
        });
    }

    /**
     * 日常任务每日刷新
     */
    public void everyRefresh() {
        everyDayTaskMap.clear();

        // 日常任务模块是否开启
        if (!CoreUtils.isFunctionUnLock(FunctionFactory.UNLOCK_EVERY_TASK, player)) {
            return;
        }

        List<TaskConfig> list = DataFactory.getInstance().getDataList(DataFactory.TASK_KEY);
        list.stream()
                .filter(v -> v.type == SGCommonProto.E_TASK_TYPE.TASK_TYPE_EVERYDAY_VALUE
                        && v.takeGrade <= player.getLv() && v.sequence == 1)
                .forEach(v -> everyDayTaskMap.put(v.id, new TaskDB(v.id)));
    }

    /**
     * 升级触发新任务
     */
    public void addNewTaskByLevelUp() {
        // 根据当前玩家已领取奖励的任务，去找是否触发下一个任务
        if (CoreUtils.isFunctionUnLock(FunctionFactory.UNLOCK_MAIN_TASK, player)) {
            for (TaskDB task : underwayMainTaskMap.values()) {
                finishTask(task);
            }
        }

        if (CoreUtils.isFunctionUnLock(FunctionFactory.UNLOCK_BRANCH_TASK, player)) {
            for (TaskDB task : underwayBranchTaskMap.values()) {
                finishTask(task);
            }
        }

        if (CoreUtils.isFunctionUnLock(FunctionFactory.UNLOCK_EVERY_TASK, player)) {
            for (TaskDB task : everyDayTaskMap.values()) {
                finishTask(task);
            }
        }

        // 增加新的支线和日常任务，如果有，则直接替换
        List<TaskConfig> list = DataFactory.getInstance().getDataList(DataFactory.TASK_KEY);
        for (TaskConfig tc : list) {
            if (tc.type == SGCommonProto.E_TASK_TYPE.TASK_TYPE_MAIN_LINE_VALUE) {
                // 主线任务不增加
                continue;
            } else if (tc.type == SGCommonProto.E_TASK_TYPE.TASK_TYPE_BRANCH_LINE_VALUE
                    && finishTasks.contains(tc.id)) {
                // 已经做过的支线任务不添加
                continue;
            }

            if (tc.sequence != 1 || tc.takeGrade > player.getLv()) {
                continue;
            }

            if (tc.type == SGCommonProto.E_TASK_TYPE.TASK_TYPE_BRANCH_LINE_VALUE
                    && CoreUtils.isFunctionUnLock(FunctionFactory.UNLOCK_BRANCH_TASK, player)
                    && !underwayBranchTaskMap.containsKey(tc.id)) {
                underwayBranchTaskMap.put(tc.id, new TaskDB(tc.id));
            } else if (tc.type == SGCommonProto.E_TASK_TYPE.TASK_TYPE_EVERYDAY_VALUE
                    && CoreUtils.isFunctionUnLock(FunctionFactory.UNLOCK_EVERY_TASK, player)
                    && !everyDayTaskMap.containsKey(tc.id)) {
                everyDayTaskMap.put(tc.id, new TaskDB(tc.id));
            }
        }

    }

    /**
     * 完成当前任务后触发下一个任务
     *
     * @param oldTaskDB
     * @return
     */
    private TaskDB finishTask(TaskDB oldTaskDB) {
        if (oldTaskDB.status != SGCommonProto.E_TASK_STATUS.TASK_STATUS_ACQUIRE_VALUE) {
            return null;
        }

        TaskConfig oldTaskConfig = oldTaskDB.getConfig();
        // 找到下一个任务
        List<TaskConfig> list = DataFactory.getInstance().getDataList(DataFactory.TASK_KEY);
        Optional<TaskConfig> op = list.stream()
                .filter(v -> v.groupId == oldTaskConfig.groupId && v.type == oldTaskConfig.type
                        && v.sequence == oldTaskConfig.sequence + 1 && v.takeGrade <= player.getLv())
                .findFirst();
        if (op.isPresent()) {
            TaskConfig nextTaskConfig = op.get();
            // 添加下一个任务
            TaskDB taskDB = new TaskDB(nextTaskConfig.id);
            if (nextTaskConfig.type == SGCommonProto.E_TASK_TYPE.TASK_TYPE_MAIN_LINE_VALUE) {
                //underwayMainTaskMap.remove(oldTaskConfig.id);
                underwayMainTaskMap.put(nextTaskConfig.id, taskDB);
            } else if (nextTaskConfig.type == SGCommonProto.E_TASK_TYPE.TASK_TYPE_BRANCH_LINE_VALUE) {
               // underwayBranchTaskMap.remove(oldTaskConfig.id);
                underwayBranchTaskMap.put(nextTaskConfig.id, taskDB);
            } else if (nextTaskConfig.type == SGCommonProto.E_TASK_TYPE.TASK_TYPE_EVERYDAY_VALUE) {
                everyDayTaskMap.remove(oldTaskConfig.id);
                everyDayTaskMap.put(nextTaskConfig.id, taskDB);
            }

            // 任务接取的时候检测是否已经完成
            BagInfo bagInfo = player.getExtInfo(BagInfo.class);
            // 通过指定关卡
            if (nextTaskConfig.target == TaskFactory.TASK_TARAGET_PASSLEVEL) {
                if (player.getInstanceData().levelHasPass(nextTaskConfig.demand[0])) {
                    taskDB.currentDemand = nextTaskConfig.showNum;
                    taskDB.status = SGCommonProto.E_TASK_STATUS.TASK_STATUS_UNCLAIMED_VALUE;
                }
            } // 主将达到指定等级
            else if (nextTaskConfig.target == TaskFactory.TASK_TARAGET_MAINUPLV) {
                taskDB.check(TaskFactory.TASK_TARAGET_MAINUPLV, player.getLv());
            } // 竞技场获胜次数，需要调用此人打的总竞技场次数
            else if (nextTaskConfig.target == TaskFactory.TASK_TARAGET_ARENA) {
                taskDB.check(TaskFactory.TASK_TARAGET_ARENA, player.getArenaData().getTotalWinCount());
            } // 检查战斗力
            else if (nextTaskConfig.target == TaskFactory.TASK_TARAGET_BATTLE_FC) {
                taskDB.check(TaskFactory.TASK_TARAGET_BATTLE_FC, player.fc);
            } // 检查拥有的卡牌 数量
            else if (nextTaskConfig.target == TaskFactory.TASK_TARAGET_CARD) {
                taskDB.check(TaskFactory.TASK_TARAGET_CARD,
                        bagInfo.getCardData().getCardMap() == null ? 0 : bagInfo.getCardData().getCardMap().size());
            } // 检查xxx件装备提升到xxx级
            else if (nextTaskConfig.target == TaskFactory.TASK_TARAGET_EQUIPINTENSIFY) {
                taskDB.check(TaskFactory.TASK_TARAGET_EQUIPINTENSIFY,
                        bagInfo.getCardData().getEquipLvCount(nextTaskConfig.demand[1]));
            }
            // x件装备合成y次
            else if (nextTaskConfig.target == TaskFactory.TASK_TARAGET_EVERYDAY_SYNC) {
                taskDB.check(TaskFactory.TASK_TARAGET_EVERYDAY_SYNC,
                        player.getBagInfo().getCardData().getEquipSyncCount(taskDB.getConfig().demand[1]));
            }
            // x件饰品达到y等级
            else if (nextTaskConfig.target == TaskFactory.TASK_TARAGET_EVERYDAY_SHIPIN) {
                taskDB.check(TaskFactory.TASK_TARAGET_EVERYDAY_SHIPIN,
                        player.getBagInfo().getCardData().getAccessoryCountByTargetLv(taskDB.getConfig().demand[1]));
            }
            // x件饰品升阶y次
            else if (nextTaskConfig.target == TaskFactory.TASK_TARAGET_EVERYDAY_SHIPIN_SHENGJIE) {
                taskDB.check(TaskFactory.TASK_TARAGET_EVERYDAY_SHIPIN_SHENGJIE,
                        player.getBagInfo().getCardData()
                                .getAccessoryUpLvCountByTargetLv(taskDB.getConfig().demand[1]));
            }
            // x个y品质及更高品质的英雄达到z星
            else if (nextTaskConfig.target == TaskFactory.TASK_TARAGET_EVERYDAY_HERO_STAR) {
                taskDB.check(TaskFactory.TASK_TARAGET_EVERYDAY_HERO_STAR,
                        player.getBagInfo().getCardData().getQualityAndStarCount(taskDB.getConfig().demand[1],
                                taskDB.getConfig().demand[2]));
            }
            return taskDB;
        }
        return null;
    }

    /***
     * 任务列表显示
     *
     * @param playerController
     * @param type
     */
    public void taskList(PlayerController playerController, SGCommonProto.E_TASK_TYPE type) {
        SGTaskProto.S2C_TaskList.Builder b = SGTaskProto.S2C_TaskList.newBuilder();
        b.setType(type);
        if (type == SGCommonProto.E_TASK_TYPE.TASK_TYPE_MAIN_LINE) {
            for (TaskDB taskDB : underwayMainTaskMap.values()) {
                b.addTaskDetail(buildTaskDetail(taskDB));
            }
        } else if (type == SGCommonProto.E_TASK_TYPE.TASK_TYPE_BRANCH_LINE) {
            for (TaskDB taskDB : underwayBranchTaskMap.values()) {
                b.addTaskDetail(buildTaskDetail(taskDB));
            }
            b.setGrowUpValue(currentGrowthValue);
            for (int i = 0; i < branchTaskBox.size(); i++) {
                b.addRewardId(branchTaskBox.get(i).intValue());
            }
        } else if (type == SGCommonProto.E_TASK_TYPE.TASK_TYPE_EVERYDAY) {
            for (TaskDB taskDB : everyDayTaskMap.values()) {
                b.addTaskDetail(buildTaskDetail(taskDB));
            }
            b.setGrowUpValue(everyActiveValue);
            for (int i = 0; i < everyDayBox.size(); i++) {
                b.addRewardId(everyDayBox.get(i).intValue());
            }
        }

        if (checkDailyTaskSendRedPoint()) {
            b.addRedPointList(SGCommonProto.E_TASK_TYPE.TASK_TYPE_EVERYDAY);
        }

        if (checkBranchTaskRedPoint()) {
            b.addRedPointList(SGCommonProto.E_TASK_TYPE.TASK_TYPE_BRANCH_LINE);
        }
        playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Task_TaskList_VALUE, b.build().toByteArray());
    }

    /***
     * 单个待领奖的任务进行领奖操作
     *
     * @param playerController
     * @param taskId
     */
    public void taskReward(PlayerController playerController, int taskId) {
        SGTaskProto.S2C_TaskReward.Builder b = SGTaskProto.S2C_TaskReward.newBuilder();
        TaskConfig taskConfig = DataFactory.getInstance().getGameObject(DataFactory.TASK_KEY, taskId);
        TaskDB taskDB = null;

        if (taskConfig.type == SGCommonProto.E_TASK_TYPE.TASK_TYPE_EVERYDAY_VALUE) {
            taskDB = everyDayTaskMap.get(taskConfig.getId());
        } else if (taskConfig.type == SGCommonProto.E_TASK_TYPE.TASK_TYPE_BRANCH_LINE_VALUE) {
            taskDB = underwayBranchTaskMap.get(taskConfig.getId());
        } else if (taskConfig.type == SGCommonProto.E_TASK_TYPE.TASK_TYPE_MAIN_LINE_VALUE) {
            taskDB = underwayMainTaskMap.get(taskConfig.getId());
        } else {
            return;
        }

        // 玩家是否有该任务
        if (taskDB == null) {
            playerController.sendWarn(WordFactory.CURRENT_TASK_IS_NULL, taskId);
            return;
        }

        // 条件是否足够
        if (taskDB.status != SGCommonProto.E_TASK_STATUS.TASK_STATUS_UNCLAIMED_VALUE) {
            playerController.sendWarn(WordFactory.FAILED_TO_MEET_THE_AWARD_CONDITIONS, taskId);
            return;
        }
        b.setTaskId(taskId);
        taskDB.status = SGCommonProto.E_TASK_STATUS.TASK_STATUS_ACQUIRE_VALUE;
        if (taskConfig.type == SGCommonProto.E_TASK_TYPE.TASK_TYPE_MAIN_LINE_VALUE) {
            currentGrowthValue += taskDB.getConfig().growthValue;
            checkBranchTaskRedPoint();
            b.setCurrentGrowthValue(currentGrowthValue);

            underwayMainTaskMap.remove(taskConfig.getId());
            finishTasks.add(taskConfig.getId());
        } else if (taskConfig.type == SGCommonProto.E_TASK_TYPE.TASK_TYPE_BRANCH_LINE_VALUE) {
            currentGrowthValue += taskDB.getConfig().growthValue;
            checkBranchTaskRedPoint();
            b.setCurrentGrowthValue(currentGrowthValue);

            // 根据类型在对应的map移除
            underwayBranchTaskMap.remove(taskConfig.getId());
            finishTasks.add(taskConfig.getId());
        } else if (taskConfig.type == SGCommonProto.E_TASK_TYPE.TASK_TYPE_EVERYDAY_VALUE) {
            everyActiveValue += taskDB.getConfig().activeValue;
            // 检测活跃值是否有可领取活跃宝箱，发送红底
            checkDailyTaskSendRedPoint();
            b.setCurrentActiveValue(everyActiveValue);
        }

        // 任务完成后下发任务
        TaskDB nextTask = finishTask(taskDB);
        if (nextTask != null) {
            SGCommonProto.TaskDetail.Builder td = SGCommonProto.TaskDetail.newBuilder();
            td.setTaskId(nextTask.id);
            td.setCurrentDemand(nextTask.currentDemand);
            td.setStatus(SGCommonProto.E_TASK_STATUS.forNumber(nextTask.status));
            b.addTaskDetail(td);
        }
        sendReward(playerController, taskConfig);
        playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Task_TaskReward_VALUE, b.build().toByteArray());

    }

    /***
     * 单个任务数据封装
     *
     * @param taskDB
     * @return
     */
    public SGCommonProto.TaskDetail.Builder buildTaskDetail(TaskDB taskDB) {
        SGCommonProto.TaskDetail.Builder td = SGCommonProto.TaskDetail.newBuilder();
        td.setTaskId(taskDB.id);
        td.setCurrentDemand(taskDB.currentDemand);
        td.setStatus(SGCommonProto.E_TASK_STATUS.forNumber(taskDB.status));
        return td;
    }

    /***
     * 背包添加任务奖励
     *
     * @param playerController
     * @param taskConfig
     */
    public void sendReward(PlayerController playerController, TaskConfig taskConfig) {
        BagInfo bagInfo = playerController.getPlayer().getExtInfo(BagInfo.class);
        for (int i = 0; i < taskConfig.assets.length; i++) {
            bagInfo.addAsset(taskConfig.assets[i].id, taskConfig.assets[i].value);
        }
        for (int i = 0; i < taskConfig.props.length; i++) {
            bagInfo.addProp(taskConfig.props[i].id, taskConfig.props[i].value);
        }
        for (int i = 0; i < taskConfig.cards.length; i++) {
            bagInfo.addCard(taskConfig.cards[i].id, taskConfig.cards[i].value);
        }
    }

    /**
     * 检测活跃值是否触发红点
     */
    private boolean checkDailyTaskSendRedPoint() {
        if (CoreUtils.isFunctionUnLock(FunctionFactory.UNLOCK_EVERY_TASK, player)) {
            // 日常任务活跃度宝箱
            List<ActiveBoxConfig> growUpBoxs = DataFactory.getInstance().getDataList(DataFactory.ACTIVE_BOX_KEY);
            for (ActiveBoxConfig box : growUpBoxs) {
                if (box.activeValue <= everyActiveValue && !everyDayBox.contains(box.getId())) {
                    player.cacheRedPoint(SGCommonProto.E_RED_POINT_TYPE.RED_POINT_TYPE_TASK);
                    return true;
                }
            }

            // 检测日常任务未领取
            for (TaskDB taskDB : everyDayTaskMap.values()) {
                if (taskDB.status == SGCommonProto.E_TASK_STATUS.TASK_STATUS_UNCLAIMED_VALUE) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 是否有主线任务可以领取
     *
     * @return
     */
    public boolean checkMainTaskRedPoint() {
        // 主线
        if (!CoreUtils.isFunctionUnLock(FunctionFactory.UNLOCK_MAIN_TASK, player)) {
            return false;
        }

        // 检测主线任务未领取
        for (TaskDB taskDB : underwayMainTaskMap.values()) {
            if (taskDB.status == SGCommonProto.E_TASK_STATUS.TASK_STATUS_UNCLAIMED_VALUE) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检测成长值是否触发红点
     */
    private boolean checkBranchTaskRedPoint() {
        if (CoreUtils.isFunctionUnLock(FunctionFactory.UNLOCK_BRANCH_TASK, player)) {
            // 支线任务活跃度宝箱
            List<GrowUpBoxConfig> growUpBoxConfigs = DataFactory.getInstance().getDataList(DataFactory.GROW_UP_BOX_KEY);
            for (GrowUpBoxConfig box : growUpBoxConfigs) {
                if (box.growthValue <= currentGrowthValue && !branchTaskBox.contains(box.getId())) {
                    player.cacheRedPoint(SGCommonProto.E_RED_POINT_TYPE.RED_POINT_TYPE_TASK);
                    return true;
                }
            }

            // 检测支线任务未领取
            for (TaskDB taskDB : underwayBranchTaskMap.values()) {
                if (taskDB.status == SGCommonProto.E_TASK_STATUS.TASK_STATUS_UNCLAIMED_VALUE) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public List<SGCommonProto.E_RED_POINT_TYPE> checkRedPointRemindAllCondition(long currentTime) {
        if (checkBranchTaskRedPoint() || checkDailyTaskSendRedPoint()) {
            List<SGCommonProto.E_RED_POINT_TYPE> list = new ArrayList<>();
            list.add(SGCommonProto.E_RED_POINT_TYPE.RED_POINT_TYPE_TASK);
            return list;
        }
        return super.checkRedPointRemindAllCondition(currentTime);
    }

    /***
     * 宝箱领取奖励
     *
     * @param playerController
     * @param type
     * @param treasureId
     */
    public void treasureReward(PlayerController playerController, int type, int treasureId) {
        GrowUpBoxConfig growUpBoxConfig = null;
        ActiveBoxConfig activeBoxConfig = null;
        GoodsData[] rewardGoods = null;
        switch (type) {
            // 日常任务
            case SGCommonProto.E_TASK_TYPE.TASK_TYPE_EVERYDAY_VALUE:
                activeBoxConfig = DataFactory.getInstance().getGameObject(DataFactory.ACTIVE_BOX_KEY, treasureId);
                if (activeBoxConfig == null) {
                    playerController.sendWarn(WordFactory.PARAM_ERROR);
                    return;
                }
                if (everyActiveValue < activeBoxConfig.activeValue) {
                    playerController.sendWarn(WordFactory.CONDITION_ERROR);
                    return;
                }
                if (everyDayBox.contains(treasureId)) {
                    // 此宝箱已经领取过
                    playerController.sendWarn(WordFactory.GET_REWARD_ED);
                    return;
                }

                everyDayBox.add(treasureId);
                rewardGoods = activeBoxConfig.getGoodsDataAry();
                break;
            // 主线任务
            case SGCommonProto.E_TASK_TYPE.TASK_TYPE_BRANCH_LINE_VALUE:
                growUpBoxConfig = DataFactory.getInstance().getGameObject(DataFactory.GROW_UP_BOX_KEY, treasureId);
                if (growUpBoxConfig == null) {
                    playerController.sendWarn(WordFactory.PARAM_ERROR);
                    return;
                }
                if (currentGrowthValue < growUpBoxConfig.growthValue) {
                    playerController.sendWarn(WordFactory.CONDITION_ERROR);
                    return;
                }
                if (branchTaskBox.contains(treasureId)) {
                    // 此宝箱已经领取过
                    playerController.sendWarn(WordFactory.GET_REWARD_ED);
                    return;
                }

                branchTaskBox.add(treasureId);
                rewardGoods = growUpBoxConfig.getGoodsDataAry();
                break;
            default:
                break;
        }
        if (rewardGoods == null) {
            playerController.sendWarn(WordFactory.PARAM_ERROR);
            return;
        }
        BagInfo bagInfo = playerController.getPlayer().getExtInfo(BagInfo.class);
        bagInfo.addGoods(rewardGoods, null);

        SGTaskProto.S2C_TreasureReward.Builder b = SGTaskProto.S2C_TreasureReward.newBuilder();
        b.setTypeValue(type);
        b.setTreasureId(treasureId);
        playerController.sendMsg(SGMainProto.E_MSG_ID.MsgID_Task_TreasureReward_VALUE, b.build().toByteArray());
    }

    public void finishAllMainTask() {
        // 清空主线任务
        underwayMainTaskMap.clear();

        List<TaskConfig> list = DataFactory.getInstance().getDataList(DataFactory.TASK_KEY);
        if (list != null) {
            for (TaskConfig taskConfig : list) {
                // 主线任务
                if (taskConfig.type == SGCommonProto.E_TASK_TYPE.TASK_TYPE_MAIN_LINE_VALUE
                        && !finishTasks.contains(taskConfig.id)) {
                    finishTasks.add(taskConfig.id);
                }
            }
        }
    }

    public void check(int taskType, int count) {
        // 主线
        if (CoreUtils.isFunctionUnLock(FunctionFactory.UNLOCK_MAIN_TASK, player)) {
            check(underwayMainTaskMap, taskType, count);
        }
        // 支线
        if (CoreUtils.isFunctionUnLock(FunctionFactory.UNLOCK_BRANCH_TASK, player)) {
            check(underwayBranchTaskMap, taskType, count);
        }
        // 每日任务
        if (CoreUtils.isFunctionUnLock(FunctionFactory.UNLOCK_EVERY_TASK, player)) {
            check(everyDayTaskMap, taskType, count);
        }
    }

    private void check(Map<Integer, TaskDB> tasks, int taskType, int count) {
        for (TaskDB taskDB : tasks.values()) {
            if (taskDB.getConfig().target == taskType
                    && taskDB.status == SGCommonProto.E_TASK_STATUS.TASK_STATUS_UNDERWAY_VALUE) {
                if (taskType == TaskFactory.TASK_TARAGET_EQUIPINTENSIFY) {
                    count = player.getBagInfo().getCardData().getEquipLvCount(taskDB.getConfig().demand[1]);
                } else if (taskType == TaskFactory.TASK_TARAGET_EVERYDAY_SYNC) {
                    count = player.getBagInfo().getCardData().getEquipSyncCount(taskDB.getConfig().demand[1]);
                } else if (taskType == TaskFactory.TASK_TARAGET_EVERYDAY_SHIPIN) {
                    count = player.getBagInfo().getCardData().getAccessoryCountByTargetLv(taskDB.getConfig().demand[1]);
                } else if (taskType == TaskFactory.TASK_TARAGET_EVERYDAY_SHIPIN_SHENGJIE) {
                    count = player.getBagInfo().getCardData()
                            .getAccessoryUpLvCountByTargetLv(taskDB.getConfig().demand[1]);
                } else if (taskType == TaskFactory.TASK_TARAGET_EVERYDAY_HERO_STAR) {
                    count = player.getBagInfo().getCardData().getQualityAndStarCount(taskDB.getConfig().demand[1],
                            taskDB.getConfig().demand[2]);
                }
                taskDB.check(taskType, count);
            }
        }
    }

    /**
     * 任务映射
     *
     * @param tasks
     */
    private void taskMapped(Map<Integer, TaskDB> tasks) {
        List<TaskDB> list = new ArrayList<>();
        Iterator<Map.Entry<Integer, TaskDB>> it = tasks.entrySet().iterator();
        while (it.hasNext()) {
            TaskDB taskDB = it.next().getValue();
            if (taskDB.getConfig().transition > 0) {
                TaskConfig newTaskConfig = DataFactory.getInstance().getGameObject(DataFactory.TASK_KEY,
                        taskDB.getConfig().transition);
                if (newTaskConfig != null) {
                    it.remove();
                    list.add(new TaskDB(newTaskConfig.id));
                }
            }
        }

        for (TaskDB newTask : list) {
            tasks.put(newTask.id, newTask);
        }
    }
}